﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Infrastructures;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Write.API.Appcation.Commands.基础设置;
using Microsoft.Data.SqlClient;
using SqlSugar;

namespace MedicalPCTerminal.Write.API.Appcation.CommandHandlers.基础设置
{
    /// <summary>
    /// 处理添加转诊配置命令
    /// </summary>
    public class AddInstitutionCommandHandler : IRequestHandler<AddInstitutionCommand, APIResult<object>>
    {
        /// <summary>
        /// sqlsugar
        /// </summary>
        private readonly SqlSugarContext sqlSugar;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="sqlSugar">sqlsugar</param>
        public AddInstitutionCommandHandler(SqlSugarContext sqlSugar,IMapper mapper)
        {
            this.sqlSugar = sqlSugar;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<object>> Handle(AddInstitutionCommand request, CancellationToken cancellationToken)
        {
                try
            {
                APIResult<object> result = new APIResult<object>();
                var entity = mapper.Map<Institution>(request);
                    var i = await sqlSugar.db.Insertable<Institution>(entity).ExecuteCommandAsync();
                    if (i > 0)
                    {
                        result.Code = APIEnum.添加成功;
                        result.Msg = APIEnum.添加成功.ToString();
                    }
                    else
                    {
                        result.Code = APIEnum.添加失败;
                        result.Msg = APIEnum.添加失败.ToString();
                        result.data = entity;
                    }
                return await Task.FromResult(result);
            }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    //try { transaction?.Rollback(); } catch { /* 忽略回滚异常 */ }
                    Console.WriteLine("事务回滚：" + ex.Message);
                    throw;
                }
            }
            
        }
    }
